using System;
using Microsoft.SPOT;

namespace codebase
{
    public class Zlib
    {
        #region Public Method

        public int Decompress(ref byte[] Scanlines, byte[] Data)
        {
            Inflator inflator = new Inflator();
            if (Data.Length < 2)
                return 53; //error, size of zlib data too small
            if ((Data[0] * 256 + Data[1]) % 31 != 0)
                return 24; //error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way
            int CM = (int)(Data[0] & 15), CINFO = (int)((Data[0] >> 4) & 15), FDICT = (int)((Data[1] >> 5) & 1);
            if (CM != 8 || CINFO > 7)
                return 25; //error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec
            if (FDICT != 0)
                return 26; //error: the specification of PNG says about the zlib stream: "The additional flags shall not specify a preset dictionary."

            byte[] tmp = new byte[Data.Length - 2];
            Array.Copy(Data, 2, tmp, 0, tmp.Length);
            Data = null;

            inflator.Inflate(ref Scanlines, tmp);
            return inflator.Error; //note: adler32 checksum was skipped and ignored
        }

        #endregion

    }
}
